﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Shapefile
{
    /// <summary>
    /// 用来表示字节序
    /// </summary>
    public enum ByteOrder
    {
        Big,
        Little
    }

    /// <summary>
    /// 解析二进制字符，对BitConverter做了进一步封装
    /// </summary>
    public static class BinaryConverter
    {
        
        public static int ToInt32(byte[] value, int startIndex, ByteOrder order)
        {
            if (value == null)
            {
                throw new ArgumentNullException("Value is Null!");
            }
            if ((startIndex + sizeof(int)) > value.Length)
            {
                throw new ArgumentException("startIndex invalid (not enough space in value to extract an integer", "startIndex");
            }

            if (BitConverter.IsLittleEndian && (order == ByteOrder.Big))
            {
                byte[] toConvert = new byte[sizeof(int)];
                Array.Copy(value, startIndex, toConvert, 0, sizeof(int));
                Array.Reverse(toConvert);
                return BitConverter.ToInt32(toConvert, 0);
            }
            else
            {
                return BitConverter.ToInt32(value, startIndex);
            }
        }

        public static double ToDouble(byte[] value, int startIndex, ByteOrder order)
        {
            if (value == null)
            {
                throw new ArgumentNullException("Value is Null!");
            }
            if ((startIndex + sizeof(double)) > value.Length)
            {
                throw new ArgumentException("startIndex invalid (not enough space in value to extract a double", "startIndex");
            }

            if (BitConverter.IsLittleEndian && (order == ByteOrder.Big))
            {
                byte[] toConvert = new byte[sizeof(double)];
                Array.Copy(value, startIndex, toConvert, 0, sizeof(double));
                Array.Reverse(toConvert);
                return BitConverter.ToDouble(toConvert, 0);
            }
            else
            {
                return BitConverter.ToDouble(value, startIndex);
            }
        }
    }
}
